package com.mohan.gulimall.product.exception;

import com.mohan.common.exception.BizCodeEnume;
import com.mohan.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * 集中处理异常
 * */
@Slf4j
//异常拦截注解
@RestControllerAdvice(basePackages = "com.mohan.gulimall.product.controller")
public class GulimallExceptionControllerAdvice {
  //需要捕获的类
  @ExceptionHandler(value = Exception.class)
  //校验规则异常
  public R handleValidExeception(MethodArgumentNotValidException e) {
    BindingResult bindingResult = e.getBindingResult();

    Map<String,String> errorMap = new HashMap<>();
    bindingResult.getFieldErrors().forEach(fieldError -> {
      errorMap.put(fieldError.getField(), fieldError.getDefaultMessage());
    });
    log.error("数据校验出现异常{},异常类型:{}",e.getMessage(),e.getClass());
    return R.error(BizCodeEnume.VALID_EXCEPTION.getCode(),BizCodeEnume.VALID_EXCEPTION.getMessage()).put("data",errorMap);
  }

  @ExceptionHandler(value = Throwable.class)
  //全局异常处理
  public R handleExeception(Exception e) {

    return R.error(BizCodeEnume.UNKNOW_EXCEPTION.getCode(), BizCodeEnume.UNKNOW_EXCEPTION.getMessage());
  }
}
